import { NextRequest } from 'next/server';
import { withMiddleware } from '@/lib/middleware/entry';
import { prisma } from '@/lib/prisma';
import { authenticateRequest } from '@/utils/auth';
import bcrypt from 'bcryptjs';

async function handler(req: NextRequest) {
  const authResult = await authenticateRequest(req);
  if (!authResult.success || !authResult.user || authResult.user.role !== 1) {
    throw new Error('权限不足');
  }

  const { username, password, email, nickname, role, status } = await req.json();

  if (!username || !password) {
    throw new Error('用户名和密码为必填项');
  }

  const existingUser = await prisma.user.findUnique({
    where: { username },
  });

  if (existingUser) {
    throw new Error('用户名已存在');
  }

  const hashedPassword = await bcrypt.hash(password, 10);

  const newUser = await prisma.user.create({
    data: {
      username,
      password: hashedPassword,
      email,
      nickname,
      role,
      status,
    },
  });

  const { password: _, ...safeUser } = newUser;

  return safeUser;
}

export const POST = withMiddleware(handler);